#include <curl/curl.h>
#include <tinyxml.h>
#include <iostream>
#include "FlickR.h"
#define URL "http://query.yahooapis.com/v1/public/yql?q="
#define TMP_FILE_NAME "temp.xml"

FILE* temp;

size_t write_data(void * ptr, size_t size, size_t nmeb, void *stream){
  return fwrite(ptr,size,nmeb,temp);
}

FlickR::FlickR(std::string user_id){
  temp = fopen(TMP_FILE_NAME,"w+");
  std::string request("select%20*%20from%20flickr.people.publicphotos%20where%20user_id=\""+user_id+"\";");

  std::string final_url(URL+request);
  /* process the file download form HTTP */
  {
    CURL* curl;
    curl = curl_easy_init();
    curl_easy_setopt(curl,CURLOPT_URL,final_url.c_str());
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,write_data);
    curl_easy_perform(curl);
    curl_easy_cleanup(curl);
  }
  fclose(temp);

  /* parse the XML downloaded file */
  {
    TiXmlDocument doc(TMP_FILE_NAME);
    doc.LoadFile();

    TiXmlHandle hDoc(&doc);
    TiXmlElement* pElem;
    TiXmlHandle hRoot(hDoc);
    {
      TiXmlElement* pResultsNode =
	hRoot.FirstChild("query").FirstChild( "results" ).FirstChild().Element();
      for( pResultsNode; 
	   pResultsNode; 
	   pResultsNode = pResultsNode->NextSiblingElement()) {
	int farm;
	int id;
	int isFamily;
	int isFriend;
	int isPublic;
	std::string* owner;
	std::string* secret;
	int server;
	std::string* title;
	
	pResultsNode->QueryIntAttribute("farm",&farm);
	pResultsNode->QueryIntAttribute("id",&id);
	pResultsNode->QueryIntAttribute("isfamily",&isFamily);
	pResultsNode->QueryIntAttribute("isfriend",&isFriend);
	pResultsNode->QueryIntAttribute("ispublic",&isPublic);
	owner = new std::string(pResultsNode->Attribute("owner"));
	
	secret = new std::string(pResultsNode->Attribute("secret"));
	pResultsNode->QueryIntAttribute("server",&server);
	title = new std::string(pResultsNode->Attribute("title"));
	
	FlickR_Img img(farm,id,(isFamily == 1),
		       (isPublic == 1),(isFriend == 1), *owner, *secret,
		       server, *title);
	
	_photo.push_back(img);
      }    
    }
  } 
    
}

void FlickR::getPictures(){

}

FlickR::~FlickR(){
  
}
